package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Account;
import csu.web.mypetstore.domain.Cart;
import csu.web.mypetstore.domain.CartItem;
import csu.web.mypetstore.domain.Item;
import csu.web.mypetstore.service.AccountService;
import csu.web.mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Iterator;

public class AddItemToCartServlet extends HttpServlet {
    private static final String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";
    private static final String SIGN_ON_FORM = "/WEB-INF/jsp/account/login&register.jsp";

    private CatalogService catalogService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        String workingItemId = "";
        if(session.getAttribute("item") != null || session.getAttribute("itemList") != null) {
            workingItemId = req.getParameter("workingItemId");
            Cart cart = (Cart) session.getAttribute("cart");
            if (cart == null) {
                cart = new Cart();
            }
            Account loginAccount = (Account) session.getAttribute("loginAccount");
            if (loginAccount == null) {
                req.getRequestDispatcher(SIGN_ON_FORM).forward(req, resp);
            } else {
                if (cart.containsItemId(workingItemId)) {
                    cart.incrementQuantityByItemId(workingItemId);
                } else {
                    catalogService = new CatalogService();
                    boolean isInStock = catalogService.isItemInStock(workingItemId);
                    Item item = catalogService.getItem(workingItemId);
                    cart.addItem(item, isInStock);
                }
                AccountService accountService = new AccountService();
                accountService.ReserveCart(loginAccount,cart);
                session.setAttribute("cart", cart);
                session.removeAttribute("item");
                session.removeAttribute("itemList");
            }
        }
            req.getRequestDispatcher(CART_FORM).forward(req,resp);
    }
}
